/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkRtspConumer.h"
#include "MkMedia/MkMediaSource.h"
#include "MkRtspSession.h"

CMkRtspConsume::CMkRtspConsume()
    : CMkMediaConsume(MkMediaConsumeRtsp)
{

}

Uint32 CMkRtspConsume::ConsumeEsPacket(CMkMediaSource* pSource, const MkEsPacket& EsPacket, Uint8* pBuf, Uint32 nLen)
{
    CMkRtspConsumer *pRtspConsumer = nullptr;
    MkMap<MkString, CMkMediaConsumer*>::iterator it = GetMapConsumer().begin();
    for (; it != GetMapConsumer().end(); it++) {
        pRtspConsumer = dynamic_cast<CMkRtspConsumer*>(it->second);
        if (!pRtspConsumer) {
            continue;
        }
        if (pRtspConsumer->IsFirstSend()) {
            CMkBufferList BufferList;
            MkEsPacket TmpEsPacket;
            MkVector<MkCacheEsPacket>::const_iterator itCache = pSource->GetCacheEsPacket().begin();
            for (; itCache != pSource->GetCacheEsPacket().end(); itCache++) {
                MkEsPacket TmpEsPacket;
                CMkMediaUtil::ReadCachePacket(*itCache, TmpEsPacket);
                pRtspConsumer->ConsumeEsPacket(TmpEsPacket, pSource->GetVideoParam(), pSource->GetAudioParam());
            }
            pRtspConsumer->SetFirstSend(FALSE);
        }
        pRtspConsumer->ConsumeEsPacket(EsPacket, pSource->GetVideoParam(), pSource->GetAudioParam());
    }
    return NoneError;
}

CMkRtspConsumer::CMkRtspConsumer(CMkRtspSession* pRtspSession)
    : CMkMediaConsumer(MkMediaConsumeRtsp)
    , m_pRtspSession(pRtspSession)
{

}

Uint32 CMkRtspConsumer::ConsumeEsPacket(const MkEsPacket& EsPacket, const CMkVideoParam& VideoParam, const CMkAudioParam& AudioParam)
{
    AddSendBytes(EsPacket.BufferList.GetTatolLen());
    if (m_pRtspSession) {
        m_pRtspSession->SendEsPacket(EsPacket, VideoParam, AudioParam);
    }
    return NoneError;
}

Uint32 CMkRtspConsumer::SessionRemoved()
{
    m_pRtspSession = nullptr;
    return NoneError;
}

void CMkRtspConsumer::Release()
{
    if (m_pRtspSession) {
        m_pRtspSession->Close();
    }
}

CMkRtspConsumer::~CMkRtspConsumer()
{
    m_pRtspSession = nullptr;
}

CMkRtspConsume::~CMkRtspConsume()
{

}